/**
 * Time:2021/12/30 18:05
 * Author:
 * Description:
 */
#include <jni.h>
#include "KMmap.h"
#include <fstream>
#include <fcntl.h>

extern "C"
JNIEXPORT jlong JNICALL
Java_com_salton123_core_HelloCpp_createFile(JNIEnv *env, jobject thiz, jstring file_path) {
    const char *savePath = env->GetStringUTFChars(file_path, 0);;
    const char *bufferPrefix = "_buf";
    char *bufferPath = (char *) malloc((strlen(savePath) + strlen(bufferPrefix)) * sizeof(char));
    strcpy(bufferPath, savePath);
    strcat(bufferPath, bufferPrefix);
    int bufferFileDescription = open(bufferPath, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    env->ReleaseStringUTFChars(file_path, savePath);
    return bufferFileDescription;
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_salton123_core_HelloCpp_getMMap(JNIEnv *env, jobject thiz, jlong file_pointer) {
    long *logBuffer = reinterpret_cast<long *>(file_pointer);
    return 0;
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_salton123_core_HelloCpp_init(JNIEnv *env, jobject thiz, jstring file_path, jint block_size) {
    const char *savePath = env->GetStringUTFChars(file_path, 0);;
    KMmap *kMmap = new KMmap(savePath, block_size);
    kMmap->initWrite();
    return reinterpret_cast<long>(kMmap);
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_salton123_core_HelloCpp_write(JNIEnv *env, jobject thiz, jlong pointer, jstring data) {
    KMmap *kMmap = reinterpret_cast<KMmap *>(pointer);
    const char *info = env->GetStringUTFChars(data, 0);
    jsize length = env->GetStringUTFLength(data);
    __android_log_print(ANDROID_LOG_INFO, "kmmap", "write:%s,length:%d", info, length);
    return kMmap->write(info, length);
}